//
//  CartView.swift
//  TanTan_Kotlin
//
//  Created by EDY on 5/26/25.
//

import SwiftUI

struct CartView:View {
    @EnvironmentObject var data: ShareProducts
    @State private var isEditing = false
    
    var body: some View {
        NavigationView {
            List {
                ForEach(data.cart) { product in
                    HStack {
                        Image(systemName: product.imageName)
                            .resizable()
                            .frame(width: 50, height: 50)
                            .cornerRadius(10)
                        VStack(alignment: .leading) {
                            Text(product.name)
                                .font(.headline)
                            Text("\(product.price, specifier: "%.2f") 元")
                                .font(.subheadline)
                        }
                    }
                }
                .onDelete(perform: removeProducts)
            }
            .navigationTitle("购物车")
            .navigationBarItems(trailing: Button(action: {
                isEditing.toggle()
            }){
                Text(isEditing ? "完成" : "编辑")
                    .foregroundColor(.blue)
                    .font(.headline)
            })
            .environment(\.editMode, isEditing ? .constant(.active) : .constant(.inactive))
        }
    }
    
    func removeProducts(at offset: IndexSet) {
        data.cart.remove(atOffsets: offset)
    }
}

#Preview {
    CartView()
}
